package com.example.demo.common;

import lombok.Builder;
import lombok.Data;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.Serializable;

@Data
@Builder
public class ResponseResult<T> {

    private T data;

    private String status;

    private String code;

    private String message;

    private long timestamp;

    public static <T> ResponseResult<T> success(T data) {
        return ResponseResult.<T>builder().data(data)
                .code(ResponseStatusCode.SUCCESS.getCode())
                .status(ResponseStatusCode.SUCCESS.getStatusCode())
                .message(ResponseStatusCode.SUCCESS.getMessage())
                .timestamp(System.currentTimeMillis())
                .build();
    }

    public static <T> ResponseResult<T> success() {
        return success(null);
    }

    /**
     * response error result wrapper.
     *
     * @param message error message
     * @param <T>     type of data class
     * @return response result
     */
    public static <T extends Serializable> ResponseResult<T> fail(String message) {
        return fail(null, message);
    }

    /**
     * response error result wrapper.
     *
     * @param data    response data
     * @param message error message
     * @param <T>     type of data class
     * @return response result
     */
    public static <T> ResponseResult<T> fail(T data, String message) {
        String msg = StringUtils.isEmpty(message) ? ResponseStatusCode.FAIL.getMessage() : message;
        return ResponseResult.<T>builder().data(data)
                .code(ResponseStatusCode.FAIL.getCode())
                .message(msg)
                .status(ResponseStatusCode.FAIL.getStatusCode())
                .timestamp(System.currentTimeMillis())
                .build();
    }

}
